package controllers

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"week3/models/mysql"
	"week3/models/request"
	"week3/pkg"
)

// 登录
func LoginUser(c *gin.Context) {
	var data request.UserRequest
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	userBool := mysql.LoginUser(data)
	if userBool.ID == 0 {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "用户不存在：：登录失败",
		})
		return
	}

	//调用jwt
	newjwt := pkg.NewJWT("2206a")
	jwtdata := pkg.CustomClaims{
		ID:       userBool.ID,
		NickName: userBool.Username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
			Subject:   "登录token",
		},
	}
	token, err := newjwt.CreateToken(jwtdata)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "生成token失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
}
